package com.atguigu.juc;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:MJS
 * @create: 2023-03-15-12:05
 * @description: 锁测试
 */
public class LockTest {
    private ReentrantLock lock = new ReentrantLock();
    //需要同步的方法
    private void method(Thread thread){
    /*    //普通的获取锁，如果锁被占用就一直等待
        lock.lock();
        try {
            System.out.println("线程名"+thread.getName()+"获得了锁");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("线程名"+thread.getName()+"释放了锁");
            lock.unlock();
        }*/
//        boolean b =false;
//        try {
//             b = lock.tryLock(1, TimeUnit.SECONDS);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        if(lock.tryLock()){
            try {
                System.out.println("线程名"+thread.getName()+"获得了锁");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println("线程名"+thread.getName()+"释放了锁");
                lock.unlock();
            }
        }else{
            System.out.println("我是"+thread.getName()+"有人占着锁，我就不要了");
        }

    }

    public static void main(String[] args) {
        LockTest lockTest = new LockTest();
        //线程1
        new Thread(()->{
            lockTest.method(Thread.currentThread());
        },"t1").start();

        //线程2
        new Thread(()->{
            lockTest.method(Thread.currentThread());
        },"t2").start();
    }

}
